﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ServerSide.EFCoreContext;
using ServerSide.Model;
using ServerSide.Model.Dto.UserDto;
using ServerSide.Model.Other;
using ServerSide.Service.Interface;

namespace ServerSide.Service
{
    public class UserService : IUserService
    {
        private readonly MyDBContext _myDBContext;
        private readonly IMapper _mapper;
        public UserService(MyDBContext myDBContext,IMapper mapper)
        {
            _myDBContext = myDBContext;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取用户数据
        /// </summary>
        /// <param name="userRequest"></param>
        /// <returns></returns>
        public PageInfo GetUsers(UserRequest userRequest)
        {
            PageInfo pageInfo = new PageInfo();

            int pageNumber = string.IsNullOrEmpty(userRequest.Page.ToString()) ? 1 : userRequest.Page;
            int pageSize = string.IsNullOrEmpty(userRequest.Size.ToString()) ? 10 : userRequest.Size;

            IQueryable<User> query = _myDBContext.User;
            //用户名匹配查询
            if (!string.IsNullOrEmpty(userRequest.UserName))
            {
                query=query.Where(n => n.UserName.Contains(userRequest.UserName));
            }

            int userTotal = query.Count();
            List<User> users = query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();

            pageInfo.Total = userTotal;
            pageInfo.DataList = users;

            return pageInfo;
        }
        /// <summary>
        /// 通过用户id获取个人主页数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public UserResponse GetPersonInfoById(int userId)
        {
            User? user = _myDBContext.User.Where(n => n.Id == userId).FirstOrDefault();

            UserRole? userRole = _myDBContext.UserRole.Where(item => item.UserId == user.Id).FirstOrDefault();
            
            Role? role = _myDBContext.Role.Where(item=>item.Id==userRole.RoleId).FirstOrDefault();
            Console.WriteLine(role.Name);
            //根据role的
            UserResponse userResponse = new UserResponse() {
                RoleName = role.Name,
                UserName=user.UserName,
                Email=user.Email,
                Phone=user.Phone,
                Gender=user.Gender,
                Birthday=user.Birthday,
                HeadPhotoPath=user.HeadPhotoPath,
                Id=user.Id,
            };
            return userResponse;
        }

        public bool AddUser(UserAdd userAdd)
        {
            User user = _mapper.Map<User>(userAdd);

            _myDBContext.User.Add(user);
            int v = _myDBContext.SaveChanges();
            if (v > 0)
            {
                User? user1 = _myDBContext.User.Where(item => item.UserName == userAdd.UserName).FirstOrDefault();
                List<UserRole> userRoles = new();
                foreach (var item in userAdd.roleIds)
                {
                    UserRole userRole = new()
                    {
                        UserId = user1.Id,
                        RoleId = item
                    };
                    userRoles.Add(userRole);
                }
                _myDBContext.UserRole.AddRange(userRoles);
                int saveSucc = _myDBContext.SaveChanges();
                if (saveSucc>0)
                {
                    return true;
                }
                return false;
            }
            return false;
        }

        public bool DelUser(User user)
        {
            bool exist = _myDBContext.User.Any(item => item.Id == user.Id);
            if (exist)
            {
                _myDBContext.User.Remove(user);
                int result = _myDBContext.SaveChanges();
                if (result>0)
                {
                    return true;
                }
            }
            return false;
        }

        public bool BatchDelUsers(List<int> ids)
        {
            try
            {
                List<User> users = _myDBContext.User.Where(item => ids.Contains(item.Id)).ToList();

                _myDBContext.User.RemoveRange(users);
                int v = _myDBContext.SaveChanges();
                if (v > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
                
            }
        }

        public bool UpdateUser(UserAdd userAdd)
        {
            User? user = _myDBContext.User.Where(item => userAdd.Id==item.Id).AsNoTracking().FirstOrDefault();
            if (user!=null)
            {
             
                user.UserName = userAdd.UserName;
                user.Password = userAdd.Password;
                user.Email = userAdd.Email;
                user.Phone = userAdd.Phone;
                user.Gender = userAdd.Gender;
                user.Enable = userAdd.Enable;
                try
                {
                    _myDBContext.User.Update(user);
                    int rowsAffected = _myDBContext.SaveChanges();

                    if (rowsAffected > 0)
                    {
                        List<UserRole> userRoles = _myDBContext.UserRole.Where(item => item.UserId == user.Id).ToList();
                        _myDBContext.UserRole.RemoveRange(userRoles);
                        _myDBContext.SaveChanges();
                        List<UserRole> addUserRoles = new();
                        foreach (var item in userAdd.roleIds)
                        {
                            UserRole userRole = new()
                            {
                                UserId = userAdd.Id,
                                RoleId = item
                            };
                            addUserRoles.Add(userRole);
                        }
                        _myDBContext.UserRole.AddRange(addUserRoles);
                        _myDBContext.SaveChanges();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
            return false;
        }

        public bool UpdateEnableOrPassword(int id, int enable, string? password)
        {
            User? user = _myDBContext.User.Where(item => item.Id == id).FirstOrDefault();
            if (user != null)
            {
                if (!string.IsNullOrEmpty(password))
                {
                    user.Password = password;
                }
                if (enable==1||enable==0)
                {
                    user.Enable = enable;
                }    
                _myDBContext.User.Update(user);
                int v = _myDBContext.SaveChanges();
                if (v > 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
